import axios from 'axios'
import { useRouter } from 'next/navigation'
import { useDispatch } from 'react-redux'
import { setUser } from '@/store/user-slice'
import { setCurProject } from '@/store/project-slice'

export const BASE_URL = 'https://api.redgrowth.app/dollars-api/public/index.php/api/'

const useRequest = () => {
  const router = useRouter()
  const dispatch = useDispatch()

  const requestInstance = axios.create({
    withCredentials: false,
    baseURL: BASE_URL,
    timeout: 60000,
    headers: {
      'Content-Type': 'application/json',
    },
  })

  requestInstance.interceptors.request.use(
    async config => {
      const user = JSON.parse(localStorage.getItem('user'))
      if (user?.token) {
        config.headers['token'] = user.token
      }
      return config
    },
    error => {
      console.log('error ==> ', error)
      return Promise.reject(error)
    }
  )

  requestInstance.interceptors.response.use(
    resp => {
      if (resp.data) {
        const code = resp.data.code
        if (code === 1) {
          return resp.data
        }

        return Promise.reject(resp.data)
      }
      return resp
    },
    error => {
      console.log('error ==> ', error)
      // Message.error('Oops! Network abnormality, try again later. Or contact admin@redgrowth.app')
      if (error.response.data.code === 10001) {
        router.replace('/')

        setTimeout(() => {
          dispatch(setUser(null))
          dispatch(setCurProject(null))
        }, 1000)
      }
      throw error
    }
  )

  return requestInstance
}

export default useRequest
